home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 6158 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.9 KB  |  71 lines

  1. Path: geog41.umd.edu!cosmo
  2. From: cosmo@Glue.umd.edu (Peter John Ersts)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Memory allocation.
  5. Date: 10 Feb 1996 21:00:28 GMT
  6. Organization: Project GLUE, University of Maryland, College Park, MD
  7. Message-ID: <4fj11c$j04@mojo.eng.umd.edu>
  8. References: <1996Feb10.161530.26449@wisipc.weizmann.ac.il>
  9. NNTP-Posting-Host: geog41.umd.edu
  10. X-Newsreader: TIN [version 1.2 PL2]
  11.  
  12. Kajdan Dimitry (cerlpvk) wrote:
  13. : I'm a starter so the question may seem stupid.
  14.  
  15. : Would someone explain why this program works?
  16.  
  17. : int* func()
  18. : {
  19. :   
  20. :   
  21. :  int b[10];
  22. :    for(int i=0;i<9;i++)
  23. :      b[i]=i;
  24. :   return b;  
  25. : }
  26.  
  27. : int main(){
  28. :   
  29. :  int* x= func();
  30. :   
  31. :   
  32. :   cout<<x[2]<<endl;
  33. :   return(1);
  34. : }
  35.  
  36. : The point is that b is allocated on the stack i.e without "new".
  37.  
  38. : Thanks in advance.
  39.  
  40.  
  41.  
  42. It works because x is an integer pointer and func() returns an integer
  43. pointer.  b gets allocated when the functions is called.
  44. :  int* func()
  45. :  {
  46. :    int b[10];
  47.  *snip*
  48.  
  49.  
  50. If you want to pass an array around you can basically just pass a pointer 
  51. to the begining of the array and reference as normal.  There is a problem 
  52. with this piece of code, because b has gone out of scope, i.e is the memory
  53. allocated for b[10] as been "put back" into the free memory pool.  It 
  54. just happens that the correct values are still there because nothing else 
  55. has been done that needs memory.
  56.  
  57.  
  58.  
  59.  
  60. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  61. Peter J. Ersts                | PHONE-HOME: (301)-422-9013
  62. Student For Life                | PHONE-WORK:  *************
  63. University of Maryland, College Park    |     E-MAIL: cosmo@eng.umd.edu
  64. ________________________________________|             stinger@wam.umd.edu
  65.  
  66. "They can't send us to hell, because we'd put it out"
  67.  
  68.        -Quote from a smokejumper getting on a bus to go back to base camp-
  69. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  70.  
  71.